<?php


namespace app\api\controller;


use app\admin\model\WithdrawLog;
use app\admin\model\Card;
use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\MoneyLog;
use think\Db;

class Withdraw extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    /**
     * 提现记录
     *
     */
    public function withdraw()
    {
        if ($this->request->isPost()) {
            $data = input('post.');
            if (empty($data['card_id'])) {
                $this->error('请选择银行卡');
            }
            if (empty($data['withdraw_price'])) {
                $this->error('请输入提款金额');
            }
            $con = Config::find(20);
            $draw = [
                'user_id' => $this->auth->id,
                'card_id' => $data['card_id'],
                'withdraw_price' => $data['withdraw_price'],
                'service_price' => $data['withdraw_price'] * $con['value'],
                'status' => 1,
            ];
            $userMoney = MoneyLog::where(['user_id' => $this->auth->id])->order('createtime desc')->find();
            $moneyLog = [
                'user_id' => $this->auth->id,
                'money' => $data['withdraw_price'],
                'before' => $userMoney['after'],
                'after' => $userMoney['after'] - $data['withdraw_price'],
                'memo' => '提现',
                'status' => -1,
                'type' => 1
            ];
            Db::startTrans();
            try {
                WithdrawLog::create($draw);
                MoneyLog::create($moneyLog);
                //商品库存变动
                \app\admin\model\User::where('id', $this->auth->id)
                    ->dec('money', $data['withdraw_price'])             //余额
                    ->update();                                              //用户余额变动
                // 提交事务
                Db::commit();
                return sucessMsg('提交申请成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return errMsg('兑换失败', $e->getMessage());
            }
        }
        return errMsg('请求错误');
    }


    /**
     * 提现记录
     *
     */
    public function log()
    {
        $user_id = $this->auth->id;
        $log = WithdrawLog::where(['user_id' => $user_id])
            ->field('id,card_id,withdraw_price,service_price,status,createtime')
            ->order('createtime desc')
            ->select();
        foreach ($log as $v) {
            $card = Card::find($v['card_id']);
            $v['card_id'] = $card['card_num'];
            $v['createtime'] = date('Y-m-d H:i', $v['createtime']);
            unset($v['card']);
        }
        $this->success('获取成功', $log);
    }
}